package org.yudidi.autoconfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.yudidi.autoconfig.condition.HelloService;
import org.yudidi.properties.HelloServiceProperties;

/**
 * 根据条件创建一些Bean.
 */
@Configuration
@EnableConfigurationProperties(HelloServiceProperties.class) //属性配置类注册到@EnableConfigurationProperties,
@ConditionalOnClass(HelloService.class) //YDD:根据HelloService在classpath中是否存在，来决定IOC容器是否自动创建该类的实例Bean
/**
 * # ConditionalOnProperty
 * ## 功能: //配置Spring Boot通过@ConditionalOnProperty来控制Configuration是否生效
 * ## 配置项:
 * 1、matchIfMissing属性：从application.properties中读取某个属性值，如果该值为空，默认值为true.
 * 2. name + havingValue属性：
 * 通过其两个属性name以及havingValue来实现的属性值的匹配验证.
 * 其中name用来从application.properties中读取某个属性值，如果该值为空，则返回false;
 * 如果值不为空，则将该值与havingValue指定的值进行比较，如果一样则返回true;否则返回false。
 * 如果返回值为false，则该configuration不生效；为true则生效
 */
@ConditionalOnProperty(prefix = "hello", name = "enable", matchIfMissing = true)//hello.enable属性没有配置则属性值默认为true.
class HelloServiceAutoConfiguration {
    @Autowired
    private HelloServiceProperties helloServiceProperties;

    /**
     * 创建一个HelloService的Bean,这个Bean的属性值来自helloServiceProperties.
     * @return
     */
    @Bean
    public HelloService helloService() {
        HelloService helloService = new HelloService();
        helloService.setMsg(helloServiceProperties.getMsg());
        return helloService;
    }
}